<script setup lang="ts">
import type { AIModel } from '@/types/Ai'
import { ref, onMounted, onUnmounted, watch } from 'vue'
import headBar from '@/pages/index/component/headBar.vue'
import my from '@/pages/my/my.vue'
import login from '@/pages/login/login.vue'
import { useMemberStore } from '@/stores/modules/member'
import SayCat from '@/pages/index/component/SayCat.vue'
// 状态管理
const memberStore = useMemberStore()

// 新增键盘高度跟踪
const keyboardHeight = ref(0)
const isKeyboardVisible = ref(false)

// 监听键盘事件
const handleKeyboardHeightChange = (res: { height: number }) => {
  keyboardHeight.value = res.height
  isKeyboardVisible.value = res.height > 0
}
// 检查登录状态
const checkedLogin = () => {
  if (!memberStore.profile) {
    console.log('未登录', goLogin.value, isPopupVisible.value)
    isPopupVisible.value = false
    goLogin.value = true
    isLogin.value = true
  } else {
    isLogin.value = false
    goLogin.value = false
    isPopupVisible.value = true
    console.log('已登录')
  }
}

// 初始化监听
onMounted(() => {
  uni.onKeyboardHeightChange(handleKeyboardHeightChange)
  checkedLogin()
})
const isPopupVisible = ref<boolean>(false)
// 清除监听
onUnmounted(() => {
  uni.offKeyboardHeightChange(handleKeyboardHeightChange)
})

// 修改后的输入容器样式计算
const inputContainerStyle = ref({
  bottom: '0px',
  transition: 'bottom 0.3s ease',
})

// 监听键盘高度变化
watch([keyboardHeight, isKeyboardVisible], ([height, visible]) => {
  if (visible) {
    inputContainerStyle.value = {
      bottom: `${height}px`,
      transition: 'bottom 0.3s ease',
    }
  } else {
    inputContainerStyle.value = {
      bottom: '0px',
      transition: 'bottom 0.3s ease 0.1s',
    }
  }
})
const showLeft = ref<boolean>(false)
const drawerRef = ref()

const showDrawer = () => {
  drawerRef.value?.open()
  checkedLogin()
}

const closeDrawer = () => {
  drawerRef.value?.close()
  uni.$emit('drawer-close')
}

const change = (e: boolean) => {
  uni.setNavigationBarTitle({ title: e ? '我的' : '首页' })
  checkedLogin()
  showLeft.value = e && !isLogin.value
  if (!e) {
    uni.$emit('drawer-close')
  }
}

// 发送消息处理
const handleSend = async () => {
  if (!inputMessage.value.trim()) return
  try {
    console.log('发送消息:', inputMessage.value)
    // await chatStore.sendMessage({
    //   content: inputMessage.value,
    //   useWebSearch: useWebSearch.value,
    // })
    Message.value = inputMessage.value
    inputMessage.value = ''
    uni.showToast({ title: '发送成功', icon: 'success' })
  } catch (err) {
    uni.showToast({ title: '发送失败', icon: 'none' })
  }
}
const Message = ref<string>('')
const inputMessage = ref('')

// 新增状态
const isRecording = ref(false)
let recorderManager: UniApp.RecorderManager | null = null
const recordingDuration = ref(0)
let recordingTimer: number | null = null

// 修改为控制输入模式的状态
const inputMode = ref<'text' | 'voice'>('text') // text-文本输入 voice-语音输入

// 优化后的语音录制处理
const startRecord = () => {
  if (isLogin.value) {
    uni.showToast({ title: '请先登录', icon: 'none' })
    isPopupVisible.value = false
    goLogin.value = true
    isLogin.value = true
    return
  }

  isRecording.value = true
  recordingDuration.value = 0
  recorderManager = uni.getRecorderManager()

  // 开始计时
  recordingTimer = setInterval(() => {
    recordingDuration.value++
  }, 1000)

  // 配置录音参数
  recorderManager.start({
    duration: 60000, // 最长录音时间，单位ms
    sampleRate: 16000, // 采样率
    numberOfChannels: 1, // 录音通道数
    encodeBitRate: 48000, // 编码码率
    format: 'mp3', // 音频格式
    frameSize: 1, // 指定帧大小
  })

  // 监听录音结束事件
  recorderManager.onStop((res) => {
    console.log('录音文件:', res.tempFilePath)
    if (res.tempFilePath) {
      handleSendVoice(res.tempFilePath)
    }
  })

  // 监听录音错误事件
  recorderManager.onError((err) => {
    console.error('录音错误:', err)
    uni.showToast({ title: '录音失败', icon: 'none' })
    isRecording.value = false
  })
}

// 处理语音文件发送
const handleSendVoice = async (filePath: string) => {
  try {
    // 显示上传中提示
    uni.showLoading({ title: '发送中...' })

    // 将录音文件转换为base64
    const base64 = await new Promise<string>((resolve, reject) => {
      uni.getFileSystemManager().readFile({
        filePath: filePath,
        encoding: 'base64',
        success: (res) => resolve(res.data as string),
        fail: reject,
      })
    })

    // 构建请求数据
    const formData = {
      audio: base64,
      type: 'voice',
      timestamp: Date.now(),
    }

    // TODO :  将数据发送到后端
    const response = await uni.request({
      url: '/api/chat/voice', // 替换为实际的API端点
      method: 'POST',
      data: formData,
      header: {
        'content-type': 'application/json',
      },
    })

    // 处理响应
    if (response.statusCode === 200) {
      uni.showToast({ title: '发送成功', icon: 'success' })
      Message.value = '[语音消息]'
    } else {
      throw new Error('发送失败')
    }
  } catch (error) {
    console.error('发送语音失败:', error)
    uni.showToast({ title: '发送失败', icon: 'none' })
  } finally {
    uni.hideLoading()
    isRecording.value = false
  }
}

const stopRecord = () => {
  if (isRecording.value) {
    recorderManager?.stop()
    if (recordingTimer) {
      clearInterval(recordingTimer)
      recordingTimer = null
    }
  }
}

// 格式化时间显示
const formatDuration = (seconds: number) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins}:${secs.toString().padStart(2, '0')}`
}

// 文件选择处理
const chooseFile = () => {
  if (isLogin.value) {
    checkedLogin()
  } else {
    uni.chooseMessageFile({
      count: 1,
      type: 'all',
      success(res) {
        console.log('已选择文件:', res.tempFiles[0])
        // 这里处理文件上传
      },
    })
  }
}

const fileList = ref<UniApp.UploadFileOption[]>([])
const isLogin = ref<boolean>(false)
const goLogin = ref<boolean>(false)
</script>

<template>
  <view class="index">
    <!-- 头部组件位置 -->
    <headBar @show-drawer="showDrawer" />

    <!-- 抽屉组件 -->
    <uni-drawer v-if="!isLogin" ref="drawerRef" mode="left" :width="280" @change="change">
      <view class="drawer-content">
        <my></my>
        <view class="close-btn" @click="closeDrawer">
          <text class="iconfont icon-close"></text>
        </view>
      </view>
    </uni-drawer>

    <!-- 聊天内容区域 -->
    <view class="chat-content"> <SayCat></SayCat> </view>

    <!-- 底部输入区域 -->
    <view class="input-container" :style="inputContainerStyle">
      <!-- 模式切换按钮 -->
      <button
        class="mode-switch"
        hover-class="button-hover"
        :disabled="isLogin"
        @click="inputMode = 'voice'"
      >
        <uni-icons custom-prefix="iconfont" :type="'mic'" size="20"></uni-icons>
      </button>

      <!-- 动态内容容器 -->
      <view class="input-content">
        <!-- 语音输入模式 -->
        <template>
          <button
            :disabled="isLogin"
            class="voice-btn"
            :class="{ recording: isRecording }"
            @touchstart="startRecord"
            @touchend="stopRecord"
            @touchcancel="stopRecord"
          >
            <text class="iconfont icon-mic"></text>
            <text class="btn-text">{{
              isRecording ? `松开发送 ${formatDuration(recordingDuration)}` : '按住说话'
            }}</text>
            <view v-if="isRecording" class="recording-indicator"></view>
          </button>
        </template>
      </view>

      <!-- 文件选择按钮 -->
      <button class="file-btn" @click="chooseFile">
        <uni-icons custom-prefix="iconfont" type="plusempty" size="20"></uni-icons>
      </button>
    </view>
    <!-- 登录弹窗 -->
    <view v-show="goLogin" class="login-popup" :class="{ 'popup-show': goLogin }">
      <login
        :isLogin="isLogin"
        v-model:isPopupVisible="isPopupVisible"
        @update:isPopupVisible="(val) => (isPopupVisible = val)"
      ></login>
    </view>
  </view>
</template>

<style lang="scss">
.index {
  padding-top: 60px;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  transition: padding-top 0.3s ease;
  position: relative;

  &.drawer-open {
    padding-top: 0;
  }
}

.login-popup {
  position: fixed;
  bottom: -100%;
  left: 0;
  right: 0;
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  z-index: 10001; /* 确保在输入区域之上 */

  &.goLogin {
    bottom: 0;
  }
}
/* 优化后的输入容器样式 */
.input-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background: #fff;
  box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.08);
  border-top: 1px solid #eee;
  gap: 8px;
  padding-bottom: calc(16px + env(safe-area-inset-bottom));
  z-index: 1000;

  .mode-switch {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: #f0f2f5;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s;
    flex-shrink: 0;

    &:active {
      background: #e4e6eb;
    }
  }

  .input-content {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 8px;
    min-height: 40px;

    .message-input {
      flex: 1;
      min-height: 40px;
      padding: 8px 16px;
      background: #f9f9f9;
      border-radius: 20px;
      font-size: 14px;
    }

    .send-btn {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background: #e4e4e4;
      display: flex;
      align-items: center;
      justify-content: center;

      &[disabled] {
        background: #ccc;
        opacity: 0.6;
      }
    }

    .voice-btn {
      flex: 1;
      height: 40px;
      border-radius: 20px;
      background: #10b981;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      position: relative;
      transition: all 0.3s;

      &.recording {
        background: #ef4444;
        transform: scale(0.98);
      }

      .btn-text {
        color: white;
        font-size: 14px;
      }

      .recording-indicator {
        position: absolute;
        right: 12px;
        top: 50%;
        transform: translateY(-50%);
        width: 8px;
        height: 8px;
        background: #fff;
        border-radius: 50%;
        animation: pulse 1s infinite;
      }
    }
  }

  .file-btn {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: #f0f2f5;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;

    &:active {
      background: #e4e6eb;
    }
  }
}

/* 暗黑模式适配 */
@media (prefers-color-scheme: dark) {
  .index {
    background-color: #1a1a1a;
  }
  .input-container {
    background: #1a1a1a;
    border-color: #333;

    .mode-switch,
    .file-btn {
      background: #2a2a2a;
      &:active {
        background: #333;
      }
    }

    .input-content {
      .message-input {
        background: #2a2a2a;
        color: #fff;
      }

      .voice-btn {
        background: #059669;
        &.recording {
          background: #dc2626;
        }
      }
    }
  }
}

@keyframes pulse {
  0%,
  100% {
    opacity: 1;
    transform: translateY(-50%) scale(1);
  }
  50% {
    opacity: 0.5;
    transform: translateY(-50%) scale(0.8);
  }
}
/* 移除旧的菜单按钮样式 */
.menu-button {
  display: none;
}

/* 新增弹窗动画 */
@keyframes slide-up {
  from {
    transform: translateY(100%);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}
</style>
